package com.ctyun.xstore.vod.common;

import java.io.IOException;
import com.alibaba.fastjson.JSON;
import com.ctyun.xstore.vod.AbstractVODResponse;
import com.ctyun.xstore.vod.exception.ServerErrorException;
import com.ctyun.xstore.vod.internal.FastJsonConfig;
import com.ctyun.xstore.vod.internal.HttpStatus;
import com.ctyun.xstore.vod.internal.OkHttpClientBuilder;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public abstract class AbstractGeneralClient {

	private final String host;

	private final String accessKey;

	private final String secretKey;

	private final OkHttpClient httpClient = OkHttpClientBuilder.singaletonClient();

	public AbstractGeneralClient(String accessKey, String secretKey) {
		this.host = "https://vod-api.xstore.ctyun.cn/xstore-vod";
		this.accessKey = accessKey;
		this.secretKey = secretKey;
	}

	public AbstractGeneralClient(String host, String accessKey, String secretKey) {
		this.host = host;
		this.accessKey = accessKey;
		this.secretKey = secretKey;
	}

	public <T extends AbstractVODResponse<?>> T execute(AbstractGeneralRequest request, Class<T> clz)
			throws IOException {
		Request req = request.buildRequest(this.host, this.accessKey, this.secretKey);

		try (Response res = httpClient.newCall(req).execute()) {
			String resBodyStr = res.body().string();
			if (res.isSuccessful()) {
				try {
					return JSON.parseObject(resBodyStr, clz, FastJsonConfig.getParseConfig());
				} catch (Exception e) {
					throw new ServerErrorException(HttpStatus.CODE_500, "VOD返回错误信息为：%s", resBodyStr);
				}
			}
			throw new ServerErrorException(res.code(), resBodyStr);
		}
	}
}
